<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>事务性内存</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/transactional_memory","wgTitle":"cpp/language/transactional memory","wgCurRevisionId":60226,"wgArticleId":10462,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["Todo without reason","Todo with reason"],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/transactional_memory","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><style type="text/css">/*<![CDATA[*/
.source-text {line-height: normal;}
.source-text li, .source-text pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for text
 * CSS class: source-text, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.text.source-text .de1, .text.source-text .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.text.source-text  {font-family:monospace;}
.text.source-text .imp {font-weight: bold; color: red;}
.text.source-text li, .text.source-text .li1 {font-weight: normal; vertical-align:top;}
.text.source-text .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.text.source-text .li2 {font-weight: bold; vertical-align:top;}
.text.source-text .ln-xtra, .text.source-text li.ln-xtra, .text.source-text div.ln-xtra {background-color: #ffc;}
.text.source-text span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_transactional_memory skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">事务性内存</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em;">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="https://zh.cppreference.com/w/cpp/container" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="statements.html" title="cpp/language/statements">语句</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="">
<tr class="t-nv-h2"><td colspan="5"> 标号 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="statements.html" title="cpp/language/statements"> <span class="t-spar">label</span> : <span class="t-spar">statement</span></a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 表达式语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="statements.html" title="cpp/language/statements"> <span class="t-spar">expression</span> ; </a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 复合语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="statements.html" title="cpp/language/statements"> { <span class="t-spar">statement</span>... } </a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 选择语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="if.html" title="cpp/language/if"> if</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="switch.html" title="cpp/language/switch"> switch</a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 循环语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="while.html" title="cpp/language/while"> while</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="do.html" title="cpp/language/do"> do-while</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="for.html" title="cpp/language/for"> for</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="range-for.html" title="cpp/language/range-for">范围 for</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 跳转语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="break.html" title="cpp/language/break"> break</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="continue.html" title="cpp/language/continue"> continue</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="return.html" title="cpp/language/return"> return</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="goto.html" title="cpp/language/goto"> goto</a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 声明语句 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="declarations.html" title="cpp/language/declarations"> <span class="t-spar">declaration</span> ; </a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> try 块 </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="try_catch.html" title="cpp/language/try catch"> try <span class="t-spar">compound-statement</span> <span class="t-spar">handler-sequence</span></a></td></tr>
<tr class="t-nv-h2"><td colspan="5"> 事务性内存 </td></tr>
<tr class="t-nv"><td colspan="5"> <strong class="selflink"> <code>synchronized</code>, <code>atomic_commit</code></strong> 等<span class="t-mark-rev t-since-tm-ts t-mark-ts">(TM TS)</span></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>事务性内存（transactional memory）是在事务中结合语句组的并发同步机制，事务具有
</p>
<ul><li> 原子性（atomic）（要么语句全部发生，要么全部不发生）
</li><li> 隔离性（isolated）（事务中的语句不会观察到另一事务写入一半，即使它们并行执行）
</li></ul>
<p>典型实现在受支持的平台上将硬件事务性内存使用到极致（例如，直至变更集饱和），再退回到软件事务性内存，后者常以乐观并发（optimistic concurrency）来实现：若另一事务更新了事务所用的某些变量，则该事务会安静地重试。由于这个原因，可重试事务（“原子块”）只能调用事务安全的函数。
</p><p>注意，在事务内和事务外访问变量而无其他的外部同步，是数据竞争。
</p><p>若支持功能特性测试，则本页所描述的功能特性，由具有大于或等于 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="nu0">201505</span></span></span> 的值的宏常量 <span class="t-c"><span class="mw-geshi cpp source-cpp">__cpp_transactional_memory</span></span> 标明。
</p>
<h3><span class="mw-headline" id=".E5.90.8C.E6.AD.A5.E5.9D.97">同步块</span></h3>
<p><code><b>synchronized</b></code> <span class="t-spar">复合语句</span>
</p><p>如同在一个全局锁下执行<a href="statements.html#.E5.A4.8D.E5.90.88.E8.AF.AD.E5.8F.A5" title="cpp/language/statements">复合语句</a>：程序中的所有最外层同步块都以一个单独的全序执行。在该顺序中，每个同步块的结尾同步于（synchronize with）下个同步块的开始。内嵌于其他同步块的同步块没有特殊语义。
</p><p>同步块不是事务（不同于后面的原子块），并可以调用事务不安全的函数。
</p>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="co2">#include &lt;vector&gt;</span>
<span class="co2">#include &lt;thread&gt;</span>
<span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw4">static</span> <span class="kw4">int</span> i <span class="sy1">=</span> <span class="nu0">0</span><span class="sy4">;</span>
    synchronized <span class="br0">{</span> <span class="co1">// 开始同步块</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> i <span class="sy1">&lt;&lt;</span> <span class="st0">" -&gt; "</span><span class="sy4">;</span>
        <span class="sy2">++</span>i<span class="sy4">;</span>       <span class="co1">// 每次调用 f() 都获得 i 的唯一值</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> i <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
        <span class="kw1">return</span> i<span class="sy4">;</span> <span class="co1">// 结束同步块</span>
    <span class="br0">}</span>
<span class="br0">}</span>
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    <a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span><a href="../thread/thread.html"><span class="kw2146">std::<span class="me2">thread</span></span></a><span class="sy1">&gt;</span> v<span class="br0">(</span><span class="nu0">10</span><span class="br0">)</span><span class="sy4">;</span>
    <span class="kw1">for</span><span class="br0">(</span><span class="kw4">auto</span><span class="sy3">&amp;</span> t<span class="sy4">:</span> v<span class="br0">)</span>
        t <span class="sy1">=</span> <a href="../thread/thread.html"><span class="kw2146">std::<span class="me2">thread</span></span></a><span class="br0">(</span><span class="br0">[</span><span class="br0">]</span><span class="br0">{</span> <span class="kw1">for</span><span class="br0">(</span><span class="kw4">int</span> n <span class="sy1">=</span> <span class="nu0">0</span><span class="sy4">;</span> n <span class="sy1">&lt;</span> <span class="nu0">10</span><span class="sy4">;</span> <span class="sy2">++</span>n<span class="br0">)</span> f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="br0">}</span><span class="br0">)</span><span class="sy4">;</span>
    <span class="kw1">for</span><span class="br0">(</span><span class="kw4">auto</span><span class="sy3">&amp;</span> t<span class="sy4">:</span> v<span class="br0">)</span>
        t.<span class="me1">join</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">0 -&gt; 1
1 -&gt; 2
2 -&gt; 3
...
99 -&gt; 100</pre></div></div> 
</div>
<p>以任何方式（抵达结尾，执行 goto、break、continue 或 return，或抛出异常）离开同步块都会退出该块，而若所退出的块是外层块，则这在单一全序中同步于下个同步块。若使用 <span class="t-lc"><a href="../utility/program/longjmp.html" title="cpp/utility/program/longjmp">std::longjmp</a></span> 退出同步块则行为未定义。
</p><p>不允许用 goto 或 switch 进入同步块。
</p><p>尽管同步块如同在一个全局锁下执行，我们仍然期待各实现检验每个块内的代码，并为事务安全代码使用乐观并发（在可用时以硬件事务性内存为后盾），为非事务安全代码使用最小锁定。当同步块调用非内联函数时，除非该函数声明为 <code>transaction_safe</code>（见下文）或使用 <code>[[optimize_for_synchronized]]</code> 属性（见下文），否则编译器可能必须放弃推测执行（spculative execution），并在整个调用周围持有一个锁。
</p>
<h3><span class="mw-headline" id=".E5.8E.9F.E5.AD.90.E5.9D.97">原子块</span></h3>
<table class="metadata plainlinks ambox mbox-small-left ambox-notice" style=""><tr><td class="mbox-empty-cell"></td><td class="mbox-text" style="">本节未完成 </td></tr></table>
<p><code><b>atomic_noexcept</b></code> <span class="t-spar">复合语句</span>
</p><p><code><b>atomic_cancel</b></code> <span class="t-spar">复合语句</span>
</p><p><code><b>atomic_commit</b></code> <span class="t-spar">复合语句</span>
</p>
<div class="t-li1"><span class="t-li">1)</span> 若抛出异常，则调用 <span class="t-c"><span class="mw-geshi cpp source-cpp"><a href="../utility/program/abort.html"><span class="kw966">std::<span class="me2">abort</span></span></a></span></span></div>
<div class="t-li1"><span class="t-li">2)</span> 若抛出异常，则调用 <span class="t-c"><span class="mw-geshi cpp source-cpp"><a href="../utility/program/abort.html"><span class="kw966">std::<span class="me2">abort</span></span></a></span></span>，除非该异常是用于事务取消的异常之一（见后述），这种情况下事务被<i>取消（cancel）</i>：程序中所有由该原子块的各操作的副作用所修改的内存位置的值，被还原到该原子块的执行开始时它们曾拥有的值，而异常照常持续栈回溯。</div>
<div class="t-li1"><span class="t-li">3)</span> 若抛出异常，则正常地提交事务。</div>
<p>用于 <code>atomic_cancel</code> 块中的事务取消的异常有 <span class="t-lc"><a href="../memory/new/bad_alloc.html" title="cpp/memory/new/bad alloc">std::bad_alloc</a></span>、<span class="t-lc"><a href="../memory/new/bad_array_new_length.html" title="cpp/memory/new/bad array new length">std::bad_array_new_length</a></span>、<span class="t-lc"><a href="../types/bad_cast.html" title="cpp/types/bad cast">std::bad_cast</a></span>、<span class="t-lc"><a href="../types/bad_typeid.html" title="cpp/types/bad typeid">std::bad_typeid</a></span>、<span class="t-lc"><a href="../error/bad_exception.html" title="cpp/error/bad exception">std::bad_exception</a></span>、<span class="t-lc"><a href="../error/exception.html" title="cpp/error/exception">std::exception</a></span> 和所有从它派生的标准库异常，以及特殊异常类型 <a href="../error/tx_exception.html" title="cpp/error/tx exception"><tt>std::tx_exception&lt;T&gt;</tt></a>。
</p><p>不允许原子块中的 <span class="t-spar">复合语句</span> 执行任何非 <code>transaction_safe</code> 的表达式或语句，或调用非 <code>transaction_safe</code> 的函数（这是编译时错误）。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co1">// 每次调用 f() 都取得 i 的唯一值，即使以并行进行</span>
<span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
   <span class="kw4">static</span> <span class="kw4">int</span> i <span class="sy1">=</span> <span class="nu0">0</span><span class="sy4">;</span>
   atomic_noexcept <span class="br0">{</span> <span class="co1">// 开始事务</span>
<span class="co1">//   printf("before %d\n", i); // 错误：不能调用非事务安全的函数</span>
      <span class="sy2">++</span>i<span class="sy4">;</span>
      <span class="kw1">return</span> i<span class="sy4">;</span> <span class="co1">// 提交事务</span>
   <span class="br0">}</span>
<span class="br0">}</span></pre></div></div>
<p>以除异常之外的任何方式（抵达结尾、goto、break、continue、return）离开原子块时，将提交事务。若用 <span class="t-lc"><a href="../utility/program/longjmp.html" title="cpp/utility/program/longjmp">std::longjmp</a></span> 退出原子块则行为未定义。
</p>
<h3><span class="mw-headline" id=".E4.BA.8B.E5.8A.A1.E5.AE.89.E5.85.A8.E7.9A.84.E5.87.BD.E6.95.B0">事务安全的函数</span></h3>
<table class="metadata plainlinks ambox mbox-small-left ambox-notice" style=""><tr><td class="mbox-empty-cell"></td><td class="mbox-text" style="">本节未完成 </td></tr></table>
<p>可在函数声明中用关键词 <span class="t-c"><span class="mw-geshi cpp source-cpp">transaction_safe</span></span> 将其显式声明为事务安全。
</p>
<table class="metadata plainlinks ambox mbox-small-left ambox-notice" style=""><tr><td class="mbox-empty-cell"></td><td class="mbox-text" style="">本节未完成 </td></tr></table><a href="lambda.html" title="cpp/language/lambda">Lambda 表达式</a>声明中，它可紧跟俘获列表之后，或紧跟关键词 <code>mutable</code> 之后（若使用它）出现。
<table class="metadata plainlinks ambox mbox-small-left ambox-notice" style=""><tr><td class="mbox-empty-cell"></td><td class="mbox-text" style="">本节未完成 </td></tr></table>
<p><br>
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw4">extern</span> <span class="kw4">volatile</span> <span class="kw4">int</span> <span class="sy2">*</span> p <span class="sy1">=</span> <span class="nu0">0</span><span class="sy4">;</span>
<span class="kw1">struct</span> S <span class="br0">{</span>
  <span class="kw1">virtual</span> ~S<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span> transaction_safe <span class="br0">{</span>
  <span class="kw4">int</span> x <span class="sy1">=</span> <span class="nu0">0</span><span class="sy4">;</span> <span class="co1">// OK：非 volatile</span>
  p <span class="sy1">=</span> <span class="sy3">&amp;</span>x<span class="sy4">;</span> <span class="co1">// OK：指针非 volatile</span>
  <span class="kw4">int</span> i <span class="sy1">=</span> <span class="sy2">*</span>p<span class="sy4">;</span> <span class="co1">// 错误：通过 volatile 泛左值读取</span>
  S s<span class="sy4">;</span> <span class="co1">// 错误：调用不安全的析构函数</span>
<span class="br0">}</span></pre></div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw4">int</span> f<span class="br0">(</span><span class="kw4">int</span> x<span class="br0">)</span> <span class="br0">{</span> <span class="co1">// 隐式事务安全</span>
  <span class="kw1">if</span> <span class="br0">(</span>x <span class="sy1">&lt;=</span> <span class="nu0">0</span><span class="br0">)</span>
    <span class="kw1">return</span> <span class="nu0">0</span><span class="sy4">;</span>
  <span class="kw1">return</span> x <span class="sy2">+</span> f<span class="br0">(</span>x<span class="sy2">-</span><span class="nu0">1</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>若通过指向事务安全函数的引用或指针调用非事务安全的函数，则行为未定义。
</p><p><br>
</p><p><br>
指向事务安全函数的指针和指向事务安全成员函数的指针分别可隐式转换为函数指针和成员函数指针。结果指针和原指针是否比较相等是未指明的。
</p>
<h4><span class="mw-headline" id=".E4.BA.8B.E5.8A.A1.E5.AE.89.E5.85.A8.E7.9A.84.E8.99.9A.E5.87.BD.E6.95.B0">事务安全的虚函数</span></h4>
<table class="metadata plainlinks ambox mbox-small-left ambox-notice" style=""><tr><td class="mbox-empty-cell"></td><td class="mbox-text" style="">本节未完成 </td></tr></table>
<p>若 <code>transaction_safe_dynamic</code> 函数的最终覆盖函数未被声明为 <code>transaction_safe</code>，则在原子块中调用它是未定义行为。
</p>
<h3><span class="mw-headline" id=".E6.A0.87.E5.87.86.E5.BA.93">标准库</span></h3>
<p>除了引入新的异常模板 <a href="../error/tx_exception.html" title="cpp/error/tx exception"><tt>std::tx_exception</tt></a> 之外，事务性内存技术规范还对标准库做出下列更改：
</p>
<ul><li> 令下列函数为显式 <code>transaction_safe</code>：
</li></ul>
<dl><dd><ul><li> <span class="t-lc"><a href="../utility/forward.html" title="cpp/utility/forward">std::forward</a></span>、<span class="t-lc">std::move</span>、<span class="t-lc"><a href="../utility/move_if_noexcept.html" title="cpp/utility/move if noexcept">std::move_if_noexcept</a></span>、<span class="t-lc"><a href="../memory/align.html" title="cpp/memory/align">std::align</a></span>、<span class="t-lc"><a href="../utility/program/abort.html" title="cpp/utility/program/abort">std::abort</a></span>、全局默认 <span class="t-lc"><a href="../memory/new/operator_new.html" title="cpp/memory/new/operator new">operator new</a></span>、全局默认 <span class="t-lc"><a href="../memory/new/operator_delete.html" title="cpp/memory/new/operator delete">operator delete</a></span>、<span class="t-lc"><a href="../memory/allocator/construct.html" title="cpp/memory/allocator/construct">std::allocator::construct</a></span>（若调用的构造函数为事务安全）、<span class="t-lc"><a href="../memory/allocator/destroy.html" title="cpp/memory/allocator/destroy">std::allocator::destroy</a></span>（若调用的析构函数为事务安全）、<span class="t-lc"><a href="../memory/get_temporary_buffer.html" title="cpp/memory/get temporary buffer">std::get_temporary_buffer</a></span>、<span class="t-lc"><a href="../memory/return_temporary_buffer.html" title="cpp/memory/return temporary buffer">std::return_temporary_buffer</a></span>、<span class="t-lc"><a href="../memory/addressof.html" title="cpp/memory/addressof">std::addressof</a></span>、<span class="t-lc"><a href="../memory/pointer_traits/pointer_to.html" title="cpp/memory/pointer traits/pointer to">std::pointer_traits::pointer_to</a></span>、所有支持事务取消的异常类型（见上文的 <code>atomic_cancel</code>）的每个非虚成员函数<table class="metadata plainlinks ambox mbox-small-left ambox-notice" style=""><tr><td class="mbox-empty-cell"></td><td class="mbox-text" style="">本节未完成<br>原因：还有更多 </td></tr></table>
</li></ul>
</dd></dl>
<ul><li> 令下列函数为显式 <code>transaction_safe_dynamic</code>
</li></ul>
<dl><dd><ul><li> 所有支持事务取消的异常类型（见上文的 <code>atomic_cancel</code>）的每个虚函数
</li></ul>
</dd></dl>
<ul><li> 要求<a href="../named_req/Allocator.html" title="cpp/named req/Allocator"><i>分配器</i> <span style="font-family: Georgia, 'DejaVu Serif', serif; font-style:italic">(Allocator)</span> </a> X 上所有事务安全的操作在 <code>X::rebind&lt;&gt;::other</code> 上亦为事务安全
</li></ul>
<h3><span class="mw-headline" id=".E5.B1.9E.E6.80.A7">属性</span></h3>
<p><code>[[<a href="attributes/optimize_for_synchronized.html" title="cpp/language/attributes/optimize for synchronized">optimize_for_synchronized</a>]]</code> 属性可应用到函数声明中的声明符中，而且必须在函数的首个声明上出现。
</p><p>若某函数在一个翻译单元中被声明为 <code>[[optimize_for_synchronized]]</code>，而同一个函数在另一翻译单元中的声明不带 <code>[[optimize_for_synchronized]]</code>，则程序非良构；不要求诊断。
</p><p>它指示函数定义应该针对从 <span class="t-c"><span class="mw-geshi cpp source-cpp">synchronized</span></span> 语句中调用而优化。具体而言，若函数对大多数的调用但非全部调用为事务安全（例如可能必须重算散列的哈希表插入、可能必须请求新内存块的分配器、可能罕有记录日志的简单函数），则该属性避免对调用该函数的同步块进行串行化。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><a href="../atomic/atomic.html"><span class="kw2066">std::<span class="me2">atomic</span></span></a><span class="sy1">&lt;</span><span class="kw4">bool</span><span class="sy1">&gt;</span> rehash<span class="br0">{</span><span class="kw2">false</span><span class="br0">}</span><span class="sy4">;</span>
 
<span class="co1">// 维护线程运行此循环</span>
<span class="kw4">void</span> maintenance_thread<span class="br0">(</span><span class="kw4">void</span><span class="sy2">*</span><span class="br0">)</span> <span class="br0">{</span>
    <span class="kw1">while</span> <span class="br0">(</span><span class="sy3">!</span>shutdown<span class="br0">)</span> <span class="br0">{</span>
        synchronized <span class="br0">{</span>
            <span class="kw1">if</span> <span class="br0">(</span>rehash<span class="br0">)</span> <span class="br0">{</span>
                hash.<span class="me1">rehash</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
                rehash <span class="sy1">=</span> <span class="kw2">false</span><span class="sy4">;</span>
            <span class="br0">}</span>
        <span class="br0">}</span>
    <span class="br0">}</span>
<span class="br0">}</span>
 
<span class="co1">// 工作线程每秒执行数十万次对此函数的调用。</span>
<span class="co1">// 从另一翻译单元中的同步块调用 insert_key() 将导致这些块被串行化，</span>
<span class="co1">// 除非标记 insert_key() 为 [[optimize_for_synchronized]]</span>
<span class="br0">[</span><span class="br0">[</span>optimize_for_synchronized<span class="br0">]</span><span class="br0">]</span> <span class="kw4">void</span> insert_key<span class="br0">(</span><span class="kw4">char</span><span class="sy2">*</span> key, <span class="kw4">char</span><span class="sy2">*</span> value<span class="br0">)</span> <span class="br0">{</span>
  <span class="kw4">bool</span> concern <span class="sy1">=</span> hash.<span class="me1">insert</span><span class="br0">(</span>key, value<span class="br0">)</span><span class="sy4">;</span>
  <span class="kw1">if</span> <span class="br0">(</span>concern<span class="br0">)</span> rehash <span class="sy1">=</span> <span class="kw2">true</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>无该属性的 GCC 汇编：串行化整个函数
</p>
<pre>insert_key(char*, char*):
	subq	$8, %rsp
	movq	%rsi, %rdx
	movq	%rdi, %rsi
	movl	$hash, %edi
	call	Hash::insert(char*, char*)
	testb	%al, %al
	je	.L20
	movb	$1, rehash(%rip)
	mfence
.L20:
	addq	$8, %rsp
	ret
</pre>
<p>有该属性的 GCC 汇编：
</p>
<pre>transaction clone for insert_key(char*, char*):
	subq	$8, %rsp
	movq	%rsi, %rdx
	movq	%rdi, %rsi
	movl	$hash, %edi
	call	transaction clone for Hash::insert(char*, char*)
	testb	%al, %al
	je	.L27
	xorl	%edi, %edi
	call	_ITM_changeTransactionMode # 注意：这是串行化点
	movb	$1, rehash(%rip)
	mfence
.L27:
	addq	$8, %rsp
	ret
</pre>
<table class="metadata plainlinks ambox mbox-small-left ambox-notice" style=""><tr><td class="mbox-empty-cell"></td><td class="mbox-text" style="">本节未完成<br>原因：检查带主干的汇编，亦显示调用方的更改 </td></tr></table>
<h3><span class="mw-headline" id=".E6.B3.A8.E8.A7.A3">注解</span></h3>
<table class="metadata plainlinks ambox mbox-small-left ambox-notice" style=""><tr><td class="mbox-empty-cell"></td><td class="mbox-text" style="">本节未完成<br>原因：来自 Wyatt 提案/讨论的体验笔记 </td></tr></table>
<h3><span class="mw-headline" id=".E7.BC.96.E8.AF.91.E5.99.A8.E6.94.AF.E6.8C.81">编译器支持</span></h3>
<p>GCC 从版本 6.1 起支持此技术规范（要求启用 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="sy2">-</span>fgnu<span class="sy2">-</span>tm</span></span>）。GCC 4.7 时曾<a rel="nofollow" class="external text" href="http://www-users.cs.umn.edu/~boutcher/stm/">支持</a>此规范的一个旧版变体。
</p>
<!-- 
NewPP limit report
Preprocessor visited node count: 2724/1000000
Preprocessor generated node count: 8376/1000000
Post‐expand include size: 46015/2097152 bytes
Template argument size: 8807/2097152 bytes
Highest expansion depth: 17/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:10462-0!*!0!!zh!2!zh!* and timestamp 20200206221414 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/transactional_memory&amp;oldid=60226">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/transactional_memory&amp;oldid=60226</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/transactional_memory">Online version</a></li><li>Offline version retrieved 2020-03-14 18:00.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2019年5月5日 (星期日) 00:55。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过8,582次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 1.133 secs. -->
	</body>
<!-- Cached 20200206221414 -->
</html>